package com.example.tests;

import com.example.framework.AccountHelper;
import com.example.framework.HibernateHelper;
import com.example.framework.JamesHelper;
import com.example.framework.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

public class SignupTests extends TestManager {

    private JamesHelper james;
    private AccountHelper accHelper;
    private HibernateHelper sqlHelper;
    private User user;

    @BeforeClass
    public void createTestData(){
        james = manager.getJamesHelper();
        accHelper = manager.getAccountHelper();
        sqlHelper =  manager.getHibernateHelper();

        createTestUser();
        createMailUser();
    }

    private void createTestUser (){
        String login = RandomStringUtils.randomAlphabetic(7);
        String password = RandomStringUtils.randomAlphanumeric(6);
        user = new User().setLogin(login).setEmail(login + "@localhost.localdomain").setPassword(password);
    }

    private void createMailUser(){
        if (! james.doesUserExist(user.login)){
            james.createUser(user.login, user.password);
        }
    }

    @AfterClass
    public void deleteMailUser(){
        if (james.doesUserExist(user.login)){
            james.deleteUser(user.login);
        }
    }

    @AfterMethod
    public void testDataCleanup(){
        manager.getHibernateHelper().deleteUser(user);
    }

    @Test
    public void shouldSignup(){
        accHelper.signup(user);
        accHelper.login(user);
        assertThat(accHelper.getLoggedUserLogin(), equalTo(user.login));
    }
}
